import os
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp

from mako.template import Template
from mako.lookup import TemplateLookup

def render(response, name, context, format=None):
	"Builds a template and writes it to the response. To keep DRY."
	
	context['user'] = users.get_current_user()
	
	if context['user']:
		context['user_action'] = 'logout'
		context['user_link'] = users.create_logout_url("/")
	else:
		context['user_action'] = 'login'
		context['user_link'] = users.create_login_url("/")
	
	# set default format
	if format is None:
		format = 'html'
		
	# render template
	#path = os.path.join(os.path.dirname(__file__), 'templates', name+'.'+format)
	mako = Template(
		filename = os.path.join(os.path.dirname(__file__), 'tpl', name+'.'+format),
		lookup = TemplateLookup(directories = ['/pci_templates'])
	)
	response.out.write(mako.render(**context))

class HomeHandler(webapp.RequestHandler):
  """ Just says hi """
  
  def get(self):
	
	context = {'title':'Examples from Programming with Collective Intelligence'}
	render(self.response, 'index', context)
 
# webapp stuff
def main():
  application = webapp.WSGIApplication([
  	('/', IndexHandler),
  	('/feeds(?:/([^.]*))?(?:\.(.*))?', FeedHandler),
  ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
